import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smart_home/pages/main/index.dart';
import 'package:smart_home/utils/color_utils.dart';
import 'package:smart_home/utils/verify/login.dart';
import 'package:smart_home/widgets/common_title_box.dart';
import 'package:smart_home/widgets/top_body.dart';
import '../../style.dart';
import './store.dart';
import '../../utils/extension/double.dart';

final textStyle1 =
    TextStyle(color: ColorsUtil.hexColor(0x6c6c6c), fontSize: 14.px);

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool checkBoxFlag = false;
  TextEditingController iphone = TextEditingController();
  TextEditingController verifyCode = TextEditingController();
  GlobalKey<FormState> _iphoneFormKey = GlobalKey<FormState>();
  GlobalKey<FormState> _verifyCodeFormKey = GlobalKey<FormState>();
  FocusNode _iphoneFocus = FocusNode();
  FocusNode _verifyCodeFocus = FocusNode();

  @override
  void initState() {
    super.initState();
    final LoginStateController loginState = Get.put(LoginStateController());
    loseFocus(_iphoneFormKey, _iphoneFocus, loginState,
        loginState.changeVerifyCodeBtnState);
    loseFocus(_verifyCodeFormKey, _verifyCodeFocus, loginState,
        loginState.changeVerifyCodeState);
  }
  
  @override
  void dispose() {
    super.dispose();
    _iphoneFocus.dispose();
    _verifyCodeFocus.dispose();
  }

  loseFocus(GlobalKey<FormState> key, FocusNode focus,
      LoginStateController loginState, Function changeState) {
    focus.addListener(() {
      if (!focus.hasFocus) {
        if (key.currentState!.validate()) {
          changeState(true);
        } else {
          changeState(false);
        }
      }
      loginState.changeLoginBtnState();
    });
  }



  @override
  Widget build(BuildContext context) {
    final LoginStateController loginState = Get.put(LoginStateController());

    return Scaffold(
        appBar: AppBar(
          // 改变header和appbar的横线
          elevation: 0,
        ),
        body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            // 点击空白区域焦点消失
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: ListView(
            children: [
              TopBody(
                content: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: commonTitleBox(),
                ),
                height: 200.px,
              ),
              Container(
                margin: EdgeInsets.all(20.px),
                child: Column(
                  children: [
                    _buildIphoneFiled(),
                    Container(
                      margin: EdgeInsets.only(top: 30.px),
                      child: _buildVerifyCodeRow(context, loginState),
                    )
                  ],
                ),
                // form
              ),
              _buildAgreementRow(loginState),
              _buildBtnBox(Obx(() => _buildLoginButton(loginState))),
              // MaterialButton(onPressed: (){})
            ],
          ),
        ));
  }

// iphone 输入框
  Form _buildIphoneFiled() {
    return Form(
        key: _iphoneFormKey,
        autovalidateMode: AutovalidateMode.disabled,
        child: TextFormField(
          controller: iphone,
          focusNode: _iphoneFocus,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            labelText: "手机号",
          ),
          validator: verifyIponeFunc,
        ));
  }

// 同意协议行
  Row _buildAgreementRow(LoginStateController loginState) {
    return Row(
      children: [
        Checkbox(
          value: checkBoxFlag,
          onChanged: (value) {
            setState(() {
              checkBoxFlag = !checkBoxFlag;
              loginState.changeCheckBoxFlag(checkBoxFlag);
              loginState.changeLoginBtnState();
            });
          },
        ),
        RichText(
          text: TextSpan(text: "我已接受并同意房至尊", style: textStyle1, children: [
            TextSpan(
                text: "隐私政策",
                style: TextStyle(decoration: TextDecoration.underline))
          ]),
        )
      ],
    );
  }

// 获取验证码行
  Row _buildVerifyCodeRow(
      BuildContext context, LoginStateController loginState) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: MediaQuery.of(context).size.width * 0.6,
          child: Form(
            key: _verifyCodeFormKey,
            autovalidateMode: AutovalidateMode.disabled,
            child: TextFormField(
              focusNode: _verifyCodeFocus,
              controller: verifyCode,
              validator: verifyCodeFunc,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(labelText: "验证码"),
            ),
          ),
        ),
        Obx(() => _buildGetCodeBtn(loginState.verifyCodeBtnState))
      ],
    );
  }

  MaterialButton _buildLoginButton(LoginStateController loginState) {
    return MaterialButton(
        height: 50.px,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(30.px))),
        onPressed: loginState.loginBtnState.value
            ? () {
                print("${iphone.text},${verifyCode.text}");
                Get.off(MainPage());
              }
            : null,
        child: Text(
          "登录 / 注册",
          style: TextStyle(color: Colors.white),
        ),
        color: themeColor,
        disabledColor: ColorsUtil.hexColor(0x89a9d2),
      );
  }

// 包裹登录按钮的盒子
  _buildBtnBox(Widget btn) {
    return Container(
      margin: EdgeInsets.only(left: 10.px, right: 10.px, top: 90.px),
      child: btn,
    );
  }

// 获取验证码按钮
  _buildGetCodeBtn(RxBool state) {
    return MaterialButton(
      height: 50.px,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(30.px)),
      ),
      onPressed: state.value
          ? () {
              print("点击");
            }
          : null,
      child: Text(
        "获取验证码",
        style: TextStyle(color: Colors.white),
      ),
      disabledColor: ColorsUtil.hexColor(0xb7b7b7),
      color: themeColor,
    );
  }
}
